package com.hanxiaozhang.graph;

/**
 * 功能描述: <br>
 * 〈生成图〉
 *
 * @Author:hanxinghua
 * @Date: 2021/9/25
 */
public class GraphGenerator {


	/**
	 * matrix 所有的边 N*3 的矩阵
	 * [
	 * [weight, from节点上面的值，to节点上面的值],
	 * [weight, from节点上面的值，to节点上面的值],
	 * [weight, from节点上面的值，to节点上面的值],
	 * ]
	 * 将如上结构转换成Graph形式
	 *
	 * @param matrix
	 * @return
	 */
	public static Graph createGraph(Integer[][] matrix) {
		Graph graph = new Graph();

		// matrix[0][0], matrix[0][1]  matrix[0][2]
		for (int i = 0; i < matrix.length; i++) {
			Integer weight = matrix[i][0];
			Integer from = matrix[i][1];
			Integer to = matrix[i][2];
			// 图中是否包含from点，不包含添加
			if (!graph.nodes.containsKey(from)) {
				graph.nodes.put(from, new Node(from));
			}
			// 图中是否包含to点，不包含添加
			if (!graph.nodes.containsKey(to)) {
				graph.nodes.put(to, new Node(to));
			}
			Node fromNode = graph.nodes.get(from);
			Node toNode = graph.nodes.get(to);
			// 创建边
			Edge newEdge = new Edge(weight, fromNode, toNode);
			// fromNode的邻居节点添加
			fromNode.nexts.add(toNode);
			// fromNode出度增加
			fromNode.out++;
			// toNode入度增加
			toNode.in++;
			// fromNode添加边
			fromNode.edges.add(newEdge);
			// graph添加边
			graph.edges.add(newEdge);
		}
		return graph;
	}

}
